import dayjs from 'dayjs'
import { ENERGY_UNITS } from '@/config'
import Cookies from 'js-cookie'

export function getThemeColor () {
  return localStorage.getItem('theme-color')
}

export function setThemeColor (color) {
  localStorage.setItem('theme-color', color)
}

export function getToken () {
  return Cookies.get('token') || localStorage.getItem('token')
}

export function setToken (token) {
  localStorage.setItem('token', token)
  Cookies.set('token', token)
}

export function removeToken () {
  localStorage.removeItem('token')
  Cookies.remove('token')
}

export function getLayoutTabsStatus () {
  return localStorage.getItem('layout-tabs-status')
}

export function setLayoutTabsStatus (status) {
  localStorage.setItem('layout-tabs-status', status)
}

export function clearStorage () {
  localStorage.clear()
}

export function getUserInfoFromStorage () {
  const userInfo = localStorage.getItem('userInfo')
  return JSON.parse(userInfo)
}

export function setUserInfoToStorage (userInfo) {
  userInfo = JSON.stringify(userInfo)
  localStorage.setItem('userInfo', userInfo)
}

export function isExternal (path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

// export const ORIGINAL_THEME_COLOR = '#00CED1' // default color
// export const ORIGINAL_THEME_COLOR = '#009e5b' // default color
// export const ORIGINAL_THEME_COLOR = '#2784f4' // default color
export const ORIGINAL_THEME_COLOR = '#08A1A3' // default color
export const ORIGINAL_THEME = ORIGINAL_THEME_COLOR

setLayoutTabsStatus(0)

export function confirmDel (vm) {
  return vm.$confirm('您确定要删除该条数据吗？', '温馨提示')
}

export function validateSelection (vm) {
  return new Promise((resolve, reject) => {
    const selection = vm.selection
    if (selection.length > 0) {
      resolve(selection)
    } else {
      vm.$message.error('请至少选择一项进行操作')
      reject(new Error('请至少选择一项进行操作'))
    }
  })
}

export const EXPIRE_TIME_STAMP_KEY = 'expire_time_stamp'
export function hasExpired () {
  const expireTimeStamp = localStorage.getItem(EXPIRE_TIME_STAMP_KEY)
  if (!expireTimeStamp) return true
  // 1小时没有更新expireTimeStamp后认为超时
  return Date.now() - 60 * 60 * 1000 > Number(expireTimeStamp)
}

export function setExpire (timestamp) {
  localStorage.setItem(EXPIRE_TIME_STAMP_KEY, timestamp)
}

export function uuid () {
  return (
    new Date().getTime().toString(16) + Math.random().toString(16).substring(2)
  ).substring(2, 18);
}

export function createMonthRangeOfYear () {
  const end = dayjs().format('YYYY-MM')
  const length = 12
  return Array(length - 1).fill(1).reduce((acc, v, i) => {
    acc.unshift(dayjs().subtract(i + 1, 'month').format('YYYY-MM'))
    return acc
  }, [end])
}
export function tree2lists (array) {
  return array.reduce((acc, { children, ...rest }) => {
    let result = [{ ...rest }]
    if (children && children.length > 0) {
      result = result.concat(tree2lists(children))
    }
    acc = acc.concat(result)
    return acc
  }, [])
}

export function lists2tree (array, id, pid) {
  const codes = array.map(v => v[id])
  const superiorCodes = [...new Set(array.map(v => v[pid]))]
  const rootCode = superiorCodes.find(v => !codes.includes(v))
  const result = array.filter(v => v[pid] === rootCode)
  let rest = array.filter(v => v[pid] !== rootCode)
  const rootCodeIndex = superiorCodes.indexOf(rootCode)

  superiorCodes.splice(rootCodeIndex, 1)

  superiorCodes.forEach((superiorCode) => {
    const children = rest.filter(v => v[pid] === superiorCode)
    const parent = result.find(v => v[id] === superiorCode)
    parent.children = children
    rest = rest.filter(v => v[pid] !== superiorCode)
  })

  return result
}

export function randomSum (n = 6, x = 100, rounding = false) {
  const rand = (m) => +((Math.random() * m).toFixed(2))
  let sum = 0
  let temp = 0
  const result = []
  for (let i = 0; i < n - 1; i++) {
    temp = rand(x - sum)
    if (rounding) {
      temp = Math.round(temp)
    }
    while (sum + temp > x) {
      temp = rand(x - sum)
    }
    sum += temp
    result.push(temp)
  }
  result.push(+((x - sum).toFixed(2)))
  return result
}

export function stringToPositiveNumber (value) {
  value = String(value)
  // 去掉首尾空格
  value = value.trim()
  // 先把非数字的都替换掉，除了数字和.
  value = value.replace(/[^0-9.]/g, '');
  // 必须保证第一个为数字而不是.
  value = value.replace(/^\./g, '');
  // 保证只有出现一个.而没有多个.
  value = value.replace(/\.{2,}/g, '.');
  // 保证.只出现一次，而不能出现两次以上
  value = value.replace('.', '$#$')
    .replace(/\./g, '')
    .replace('$#$', '.')
  return value
}

export function formatNumber (number) {
  return Number(number).toLocaleString()
}

const ACCOUNT_PASSWORD_KEY = 'ACCOUNT_PASSWORD_KEY'
export function getAccountPwd () {
  return localStorage.getItem(ACCOUNT_PASSWORD_KEY)
}
export function setAccountPwd (data) {
  return localStorage.setItem(ACCOUNT_PASSWORD_KEY, data)
}

export function getEnergyUnitName (type) {
  const energyUnits = ENERGY_UNITS.slice()
  const target = energyUnits.find(v => v.key === type)
  return target ? target.value : '吨标准煤'
}

// TODO
export function pieTooltipFormatter ({ color, percent, name, value, data, ...rest }) {
  return `
    <div style="margin: 0;line-height:1;">
      <div style="font-size:14px;color:#666;font-weight:400;line-height:1;">${rest.seriesName || name}</div>
      <div style="margin: 10px 0 0;line-height:1;">
        <div style="margin: 0;line-height:1.5;">
          <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>
          <span style="font-size:14px;color:#666;font-weight:400;margin-left:2px">${name}：</span>
          <span style="font-size:14px;color:#666;font-weight:900">${defaultNumber(value)} ${data ? data.unit || '' : ''}（${percent}%）</span>
       </div>
      </div>
    </div>
  `
}

/**
 * 自动填充接口未返回的日数据
 * @param length{number} 月份天数
 * @param data{object[]}
 * @param pattern{RegExp}
 * @param nameKey{string}
 * @param valueKey{string}
 * @param string{string}
 * @returns {any[]}
 */
export function simpleAutoFill (length, data, pattern = /\d{4}-\d{2}-(\d{2})/, nameKey = 'name', valueKey = 'val', string = '-') {
  const result = Array(length).fill(string)
  data.forEach(v => {
    const name = v[nameKey]
    const m = (name || '').replace(pattern, (p, m) => m)
    result.splice(Number(m) - 1, 1, v[valueKey])
  })
  return result
}

// 判断是否为'' null undefined
export function isEmpty (value) {
  return value === '' || value == null
}
// 默认填充数值
export function defaultNumber (number, string = '-', useFormat = true) {
  number = isEmpty(number) ? string : number
  return (useFormat && number !== string) ? formatNumber(number) : number
}
